<template>
  <div class="game-wrapper">
    <div class="game-container">
      <div class="header" v-if="!gameStarted">
        <h1 class="title">单词地鼠</h1>
        <button 
          @click="startGame" 
          :disabled="gameStarted"
          class="start-btn"
        >
          开始游戏
        </button>
      </div>
      <div id="gameCanvas"></div>
    </div>
  </div>
</template>

<script>
import Phaser from 'phaser'

class WhackAMoleScene extends Phaser.Scene {
  constructor() {
    super({ key: 'WhackAMoleScene' })
    console.log('WhackAMoleScene 场景创建')
    this.hammer = null
    this.holes = []
    this.moles = []
    this.wordPairs = [
      { eng: 'apple', chn: '苹果' },
      { eng: 'book', chn: '书' },
      { eng: 'cat', chn: '猫' },
      { eng: 'dog', chn: '狗' },
      { eng: 'elephant', chn: '大象' }
    ]
    this.currentWord = null
    this.score = 0
    this.scoreText = null
    this.isHitting = false
    this.questionStartTime = 0  // 添加题目开始时间
    this.questionTimeText = null  // 添加题目计时器显示
  }

  create() {
    console.log('场景 create 方法开始执行')
    // 设置背景色
    this.cameras.main.setBackgroundColor('#8aaf7c')

    // 获取游戏尺寸
    const width = this.game.config.width
    const height = this.game.config.height
    const isMobile = width < 768

    // 调整布局参数
    const centerX = width / 2
    const centerY = height / 2
    const isLandscape = width > height
    
    // 根据屏幕方向调整半圆大小
    const radius = isMobile 
      ? (isLandscape 
        ? Math.min(width * 0.3, height * 0.6) // 横屏时调整半径
        : Math.min(width, height) * 0.3)
      : 200

    // 调整分数显示位置，确保不被遮挡
    this.scoreText = this.add.text(20, 20, '分数: 0', {
      fontSize: isMobile ? '24px' : '32px',
      fill: '#fff',
      stroke: '#000',
      strokeThickness: 4,
      backgroundColor: 'rgba(0, 0, 0, 0.3)',
      padding: { x: 10, y: 5 }
    })

    // 调整计时器显示位置
    this.questionTimeText = this.add.text(
      width - 20, 
      20, 
      '用时: 0s', 
      {
        fontSize: isMobile ? '20px' : '24px',
        fill: '#fff',
        stroke: '#000',
        strokeThickness: 4,
        backgroundColor: 'rgba(0, 0, 0, 0.3)',
        padding: { x: 10, y: 5 }
      }
    ).setOrigin(1, 0)

    // 调整中心词位置，横屏时稍微上移
    const wordY = isLandscape ? centerY * 0.8 : centerY
    this.currentWordText = this.add.text(centerX, wordY, '', {
      fontSize: isMobile ? '28px' : '32px',
      fill: '#fff',
      stroke: '#000',
      strokeThickness: 4,
      backgroundColor: 'rgba(33, 150, 243, 0.4)',
      padding: { x: 15, y: 8 },
      borderRadius: 8
    }).setOrigin(0.5)

    // 添加文字的光晕效果
    const glow = this.add.circle(centerX, wordY, 60, 0x2196f3, 0.1)
    glow.setDepth(-1)
    
    // 添加文字的光晕动画
    this.tweens.add({
      targets: glow,
      scale: 1.2,
      alpha: 0.05,
      duration: 1500,
      yoyo: true,
      repeat: -1,
      ease: 'Sine.easeInOut'
    })

    // 创建半圆形洞的布局，横屏时调整起始角度
    const startAngle = isLandscape ? Math.PI * 0.8 : Math.PI
    const endAngle = isLandscape ? Math.PI * 0.2 : 0
    
    const holeCount = 5

    // 创建半圆形洞的布局
    for (let i = 0; i < holeCount; i++) {
      const t = i / (holeCount - 1)
      const angle = startAngle + (endAngle - startAngle) * t
      const x = centerX + Math.cos(angle) * radius
      const y = centerY + Math.sin(angle) * radius
      
      // 创建洞
      const hole = this.add.circle(x, y, 30, 0x000000, 0.3)
      this.holes.push(hole)
      
      // 创建地鼠
      const mole = this.add.container(x, y)
      const moleBody = this.add.circle(0, 0, 22, 0x8B6B62)
      const moleEyes = this.add.circle(-7, -8, 4, 0xF5F5F5)
      const moleEyes2 = this.add.circle(7, -8, 4, 0xF5F5F5)
      const moleNose = this.add.circle(0, -4, 2.5, 0x333333)
      mole.add([moleBody, moleEyes, moleEyes2, moleNose])
      mole.setVisible(false)
      
      this.moles.push(mole)
    }

    // 创建锤子（使用图形绘制）
    this.hammer = this.add.container(400, 300)
    
    // 锤子头
    const hammerHead = this.add.rectangle(0, -20, 40, 30, 0x666666)
    
    // 锤子柄
    const hammerHandle = this.add.rectangle(0, 10, 8, 60, 0x8B4513)
    
    this.hammer.add([hammerHead, hammerHandle])
    this.hammer.setVisible(false)

    // 添加鼠标点击监听
    this.input.on('pointerdown', (pointer) => {
      if (!this.isHitting) {
        this.hit(pointer)
      }
    })

    // 开始游戏循环
    this.startMoleLoop()
    console.log('场景初始化完成')
  }

  startMoleLoop() {
    // 记录开始时间
    this.questionStartTime = Date.now()

    // 获取游戏尺寸和移动端标志
    const width = this.game.config.width
    const height = this.game.config.height
    const isMobile = width < 768

    // 如果是新一轮（而不是刷新选项），才更新中心词
    if (!this.currentWord) {
      const currentPair = this.wordPairs[Phaser.Math.Between(0, this.wordPairs.length - 1)]
      this.currentWord = currentPair.eng
      this.currentWordText.setText(currentPair.eng)
      
      // 只在第一次显示时添加缩放动画
      if (!this.currentWordText.tween) {
        this.currentWordText.tween = this.tweens.add({
          targets: this.currentWordText,
          scale: 1.1,
          duration: 800,
          yoyo: true,
          repeat: -1,
          ease: 'Sine.easeInOut'
        })
      }
    }

    // 准备不重复的选项
    const currentPair = this.wordPairs.find(p => p.eng === this.currentWord)
    const options = [currentPair.chn]
    const usedWords = new Set([currentPair.chn])
    const availableWords = this.wordPairs
      .filter(pair => pair.eng !== this.currentWord)
      .map(pair => pair.chn)
    
    // 随机选择2-3个不重复的错误选项
    const wrongCount = Phaser.Math.Between(2, 3)
    while (options.length < wrongCount + 1 && availableWords.length > 0) {
      const index = Phaser.Math.Between(0, availableWords.length - 1)
      const word = availableWords.splice(index, 1)[0]
      if (!usedWords.has(word)) {
        options.push(word)
        usedWords.add(word)
      }
    }

    // 打乱选项顺序
    Phaser.Utils.Array.Shuffle(options)

    // 显示地鼠和选项
    options.forEach((text, index) => {
      const mole = this.moles[index]
      const originalY = mole.y
      
      mole.text = this.add.text(mole.x, originalY - (isMobile ? 20 : 25), text, {
        fontSize: isMobile ? '20px' : '24px',
        fill: '#fff',
        stroke: '#000',
        strokeThickness: 4,
        backgroundColor: 'rgba(0, 0, 0, 0.3)',
        padding: { x: isMobile ? 8 : 10, y: isMobile ? 2 : 3 }
      }).setOrigin(0.5)

      // 设置初始位置和显示
      mole.setVisible(true)
      mole.y = originalY + 30  // 使用相对于原始位置的偏移
      mole.alpha = 0
      mole.text.alpha = 0
      
      // 弹出动画
      this.tweens.add({
        targets: [mole, mole.text],
        y: `-=${30}`,  // 使用相对位移
        alpha: 1,
        duration: 300,
        ease: 'Back.out',
        onComplete: () => {
          // 确保位置正确
          mole.y = originalY
          mole.text.y = originalY - 25
          
          // 添加呼吸动画（只改变缩放，不改变位置）
          this.tweens.add({
            targets: mole,
            scaleX: 1.05,
            scaleY: 0.95,
            duration: 1000,
            yoyo: true,
            repeat: -1,
            ease: 'Sine.easeInOut'
          })
        }
      })
    })

    // 添加计时器更新
    this.time.addEvent({
      delay: 100,
      callback: this.updateQuestionTime,
      callbackScope: this,
      loop: true
    })
  }

  updateQuestionTime() {
    const elapsed = Math.floor((Date.now() - this.questionStartTime) / 1000)
    this.questionTimeText.setText(`用时: ${elapsed}s`)
  }

  hit(pointer) {
    console.log('点击事件触发:', pointer.x, pointer.y)
    if (this.isHitting) return
    this.isHitting = true
    
    // 显示锤子动画
    this.hammer.setVisible(true)
    this.hammer.x = pointer.x
    this.hammer.y = pointer.y
    this.hammer.rotation = -Math.PI / 4
    
    this.tweens.add({
      targets: this.hammer,
      rotation: Math.PI / 4,
      duration: 150,
      ease: 'Power2',
      yoyo: true,
      onComplete: () => {
        this.hammer.setVisible(false)
        this.isHitting = false
      }
    })

    // 检查是否击中地鼠
    this.moles.forEach(mole => {
      if (mole.visible && Phaser.Geom.Rectangle.Contains(
        mole.getBounds(),
        pointer.x,
        pointer.y
      )) {
        const originalY = mole.y
        
        if (mole.text.text === this.wordPairs.find(p => p.eng === this.currentWord).chn) {
          // 正确答案处理
          this.score += 10
          this.scoreText.setText('分数: ' + this.score)
          this.showFeedback('正确! +10', true)
          
          // 淡出动画
          this.tweens.add({
            targets: [mole, mole.text],
            alpha: 0,
            duration: 300,
            ease: 'Power2',
            onComplete: () => {
              // 清理当前所有地鼠
              this.moles.forEach(m => {
                if (m.text) m.text.destroy()
                m.setVisible(false)
                m.setAlpha(1)
              })
              // 延迟一下再开始新题，让玩家看清正确反馈
              this.time.delayedCall(500, () => {
                // 重置当前词，开始新一轮
                this.currentWord = null
                this.startMoleLoop()
              })
            }
          })
        } else {
          // 错误答案处理
          this.showFeedback('错误! 请重试', false)
          
          // 错误答案动画
          this.tweens.add({
            targets: mole,
            angle: { from: -10, to: 10 },
            duration: 100,
            repeat: 3,
            yoyo: true,
            onComplete: () => {
              mole.angle = 0
              // 显示正确答案提示
              const correctPair = this.wordPairs.find(p => p.eng === this.currentWord)
              const correctMole = this.moles.find(m => 
                m.visible && m.text && m.text.text === correctPair.chn
              )
              if (correctMole) {
                // 高亮显示正确答案
                this.tweens.add({
                  targets: correctMole,
                  scaleX: 1.3,
                  scaleY: 1.3,
                  duration: 200,
                  yoyo: true,
                  repeat: 2
                })
              }
            }
          })
        }
      }
    })
  }

  showFeedback(text, isSuccess) {
    const isMobile = this.game.config.width < 768
    const isLandscape = this.game.config.width > this.game.config.height
    
    // 调整提示文本位置，确保在视野内
    const y = isLandscape 
      ? this.game.config.height * 0.3 
      : this.game.config.height * 0.4

    const feedbackText = this.add.text(
      this.game.config.width / 2, 
      y,
      text, 
      {
        fontSize: isMobile ? '36px' : '48px',
        fontWeight: 'bold',
        fill: isSuccess ? '#4CAF50' : '#F44336',
        stroke: '#000',
        strokeThickness: 6,
        shadow: { blur: 10, color: '#000', fill: true }
      }
    ).setOrigin(0.5)

    // 添加动画效果
    this.tweens.add({
      targets: feedbackText,
      scale: { from: 0.5, to: 1 },
      alpha: { from: 0, to: 1 },
      duration: 300,
      ease: 'Back.out',
      onComplete: () => {
        this.tweens.add({
          targets: feedbackText,
          scale: { from: 1, to: 1.2 },
          alpha: { from: 1, to: 0 },
          duration: 500,
          delay: 500,
          ease: 'Power2',
          onComplete: () => {
            feedbackText.destroy()
          }
        })
      }
    })
  }
}

export default {
  name: 'MatchingGame',
  data() {
    return {
      game: null,
      gameStarted: false
    }
  },
  methods: {
    startGame() {
      console.log('开始游戏按钮被点击')
      // 防止重复点击
      if (this.gameStarted) {
        console.log('游戏已经开始，忽略重复点击')
        return
      }

      // 标记游戏已开始
      this.gameStarted = true
      console.log('游戏状态已设置为开始')

      // 延迟创建游戏实例，确保DOM已经更新
      this.$nextTick(() => {
        console.log('DOM更新完成，开始初始化游戏')
        try {
          const isMobile = window.innerWidth < 768 || /Mobile|Android|iPhone/i.test(navigator.userAgent)
          console.log('设备检测:', isMobile ? '移动设备' : '桌面设备')
          console.log('屏幕尺寸:', window.innerWidth, 'x', window.innerHeight)
          
          // 根据屏幕大小设置游戏尺寸
          let width, height
          if (isMobile) {
            const isLandscape = window.innerWidth > window.innerHeight
            console.log('屏幕方向:', isLandscape ? '横屏' : '竖屏')
            if (isLandscape) {
              height = Math.max(450, window.innerHeight)
              width = Math.min(window.innerWidth, height * 1.5)
            } else {
              width = window.innerWidth
              height = Math.min(window.innerHeight, window.innerWidth * 1.5)
            }
          } else {
            width = 800
            height = 600
          }
          console.log('游戏画布尺寸:', width, 'x', height)
          
          const config = {
            type: Phaser.AUTO,
            parent: 'gameCanvas',
            width,
            height,
            scene: WhackAMoleScene,
            scale: {
              mode: Phaser.Scale.FIT,
              autoCenter: Phaser.Scale.CENTER_BOTH
            },
            input: {
              touch: {
                capture: true
              }
            },
            render: {
              transparent: true,
              antialias: true,
              pixelArt: false
            }
          }
          console.log('游戏配置:', config)

          // 销毁旧的游戏实例（如果存在）
          if (this.game) {
            console.log('销毁旧的游戏实例')
            this.game.destroy(true)
          }

          console.log('开始创建新的游戏实例')
          this.game = new Phaser.Game(config)
          console.log('游戏实例创建成功')

          // 监听屏幕旋转
          window.addEventListener('resize', this.handleResize)
          console.log('已添加屏幕旋转监听')

        } catch (error) {
          console.error('游戏初始化错误:', error)
          console.error('错误堆栈:', error.stack)
          this.gameStarted = false
          alert('游戏启动失败，请刷新页面重试')
        }
      })
    },

    handleResize() {
      console.log('屏幕尺寸变化')
      console.log('新尺寸:', window.innerWidth, 'x', window.innerHeight)
      if (this.game) {
        const isMobile = window.innerWidth < 768
        let width, height
        
        if (isMobile) {
          const isLandscape = window.innerWidth > window.innerHeight
          if (isLandscape) {
            height = Math.max(450, window.innerHeight)
            width = Math.min(window.innerWidth, height * 1.5)
          } else {
            width = window.innerWidth
            height = Math.min(window.innerHeight, window.innerWidth * 1.5)
          }
        } else {
          width = 800
          height = 600
        }
        
        this.game.scale.resize(width, height)
      }
    },

    handleGameError(error) {
      console.error('Game error:', error)
      if (this.game) {
        this.game.destroy(true)
      }
      this.gameStarted = false
      alert('游戏出现错误，请刷新页面重试')
    }
  },
  mounted() {
    console.log('组件已挂载')
    window.addEventListener('orientationchange', this.checkOrientation)
  },
  beforeDestroy() {
    console.log('组件即将销毁')
    if (this.game) {
      console.log('销毁游戏实例')
      this.game.destroy(true)
    }
    window.removeEventListener('resize', this.handleResize)
    window.removeEventListener('orientationchange', this.checkOrientation)
  }
}
</script>

<style scoped>
.game-wrapper {
  min-height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #1a1a1a;
  overflow: auto;
  -webkit-overflow-scrolling: touch;
  /* 防止微信下拉刷新 */
  position: fixed;
  top: 0;
  left: 0;
}

.game-container {
  width: 100%;
  height: 100vh;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 450px;
}

@media (min-width: 768px) {
  .game-container {
    width: 800px;
    height: 600px;
  }
}

.header {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: white;
  z-index: 1;
  width: 90%;
  max-width: 400px;
}

.title {
  font-size: clamp(32px, 8vw, 48px);
  margin-bottom: 20px;
  text-shadow: 0 2px 4px rgba(0,0,0,0.5);
}

.start-btn {
  padding: clamp(10px, 3vw, 15px) clamp(20px, 5vw, 30px);
  font-size: clamp(18px, 5vw, 24px);
  background: linear-gradient(145deg, #4caf50, #45a049);
  border: none;
  border-radius: 8px;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  /* 优化点击效果 */
  -webkit-tap-highlight-color: transparent;
  user-select: none;
  -webkit-user-select: none;
}

.start-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}

.start-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

#gameCanvas {
  width: 100%;
  height: 100%;
  touch-action: pan-x pan-y;
  min-height: 450px;
  /* 优化微信环境下的触摸响应 */
  -webkit-tap-highlight-color: transparent;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  user-select: none;
}

/* 横屏时的特殊处理 */
@media (orientation: landscape) and (max-height: 450px) {
  .game-wrapper {
    min-height: 450px;
    height: auto;
  }

  .game-container {
    height: 450px;
    margin: 20px 0;
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .game-container {
    width: 100vw;
    height: 100vh;
  }

  .header {
    padding: 10px;
  }

  .title {
    font-size: clamp(24px, 5vw, 32px);
    margin-bottom: 10px;
  }

  .start-btn {
    padding: clamp(8px, 2vw, 12px) clamp(16px, 4vw, 24px);
    font-size: clamp(16px, 4vw, 20px);
  }
}
</style> 